<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      :showCollapse="true"
      v-model:form-value="state.query"
      :exclude-values="[
        'userCName',
        'groupCname',
        'cyrUserCName',
        'startName',
        'startTimeBegin',
        'startTimeEnd',
        'endTimeBegin',
        'endTimeEnd',
      ]"
      :table-column="columns"
      :wrapperSpan="8"
      @submit="searchFn"
      @reset="resetFn"
    >
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="compCname" label="流程参与人">
          <!-- <FIInput v-model="state.query.compCname" clearable /> -->
          <FIAutoInput
            v-model="state.query.cyrUserCName"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'cyr')"
            @change="changeEvent($event, 'cyr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="startTime" label="流程开始时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="daterange"
            placeholder=""
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="endTime" label="流程结束时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="daterange"
            placeholder="流程结束时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="instStatus" label="流程状态">
          <FISelect v-model="state.query.instStatus" valueCustom="value" :options="processStatus" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="sequenceId" label="流程实例号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="processDefKey" label="流程名称">
          <FISelect v-model="state.query.processDefKey" valueCustom="value" :options="processArr" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="productNo" label="产品号">
          <FIInput v-model="state.query.productNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="productName" label="产品名称">
          <FISelect
            v-model="state.query.productName"
            :options="productList"
            popperClass="select-loginName-class"
            :props="{ value: 'productName', label: 'productName' }"
            :display-key="['productNo', 'productName']"
            valueCustom="productName"
            @select="selectClick($event, 'product')"
            clearable
            filterable
            usePagination
            @load-more="productloadMore"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="projectNo" label="项目号">
          <FIInput v-model="state.query.projectNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="projectName" label="项目名称">
          <FIInput v-model="state.query.projectName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="contractNo" label="合同号">
          <FIInput v-model="state.query.contractNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="contractName" label="合同名称">
          <FIInput v-model="state.query.contractName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="starter" label="流程发起人">
          <FIAutoInput
            v-model="state.query.userCName"
            :options="userList"
            value-key="userCName"
            :displayKey="['loginName', 'userCName']"
            @select="selectClick($event, 'fqr')"
            @change="changeEvent($event, 'fqr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="instSubject" label="业务说明">
          <FIInput v-model="state.query.instSubject" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="startApp" label="发起系统">
          <FIAutoInput
            v-model="state.query.startName"
            :options="appDataList"
            :props="{ value: 'appCode', label: 'appName' }"
            :display-key="['appCode', 'appName']"
            @select="selectClick($event, 'fqxt')"
            @change="changeEvent($event, 'fqxt')"
          >
            <!-- <template #default="{ item }">
              <div>{{ item.appCode }} {{ item.appName }}</div>
            </template> -->
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="8" class="flex-center">
        <FIFormItem prop="authType" label="权限类型">
          <FISelect v-model="state.query.authType" valueCustom="value" :options="authTypeArr" clearable />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="流程实例记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="processInstanceId"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :showSaveModel="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <FIButton border @click="btnClick('ALL')">按查询条件授权</FIButton>
        <FIButton border @click="btnClick('SELECT')">选择记录授权</FIButton>
        <FIButton border @click="deleteRow">删除流程实例授权</FIButton>
      </template>
    </FITable>
    <FIModel v-model="selectDiag" width="500" title="选择授权人">
      <FIFormItem label="授权人">
        <FIAutoInput
          v-model="userCName"
          :options="userList"
          value-key="userCName"
          :displayKey="['loginName', 'userCName']"
          @select="selectClick($event, 'sqr')"
          @change="changeEvent($event, 'sqr')"
        >
          <template #default="{ item }">
            <div>{{ item.loginName }} {{ item.userCName }}</div>
          </template>
        </FIAutoInput>
      </FIFormItem>
      <template #footer>
        <slot name="footer">
          <div class="dialog-footer">
            <el-button class="margin-left5" border @click="selectConfirm">保存</el-button>
            <FIButton @click="selectDiag = false">取消</FIButton>
          </div>
        </slot>
      </template>
    </FIModel>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FITable from '@/components/FITable/index.vue'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import DeptTree from '../../components/DeptTree'

import {
  apiQueryUser,
  apiQueryDept,
  apiQueryAuth,
  apiProcAuthInstAuth,
  apiDeleteAuth,
  apiQueryProcessesDef,
  apiQueryAllBpmCatogary,
  apiQueryApp,
  apiQueryProduct,
} from '@/api/modules/EW.js'
const route = useRoute()
const isTableLoading = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const selectDiag = ref(false)
const tableRef = ref(null)
const userList = ref([])
const deptList = ref([])
const userCName = ref('')
const userObj = ref({})
const authMode = ref('')
const processArr = ref([])
const appDataList = ref([])
const productList = ref([])
const productPage = ref(1)
const loadMoreEnd = ref(false)
const authTypeArr = [
  {
    value: 'Self',
    label: '参与经办流程',
  },
  {
    value: 'ByProcInst',
    label: '通过流程实例授权流程',
  },
  {
    value: 'ByProcDef',
    label: '通过流程定义授权流程',
  },
]
const processStatus = [
  {
    value: 'active',
    label: '正运行',
  },
  {
    value: 'suspend',
    label: '挂起',
  },
  {
    value: 'finish',
    label: '结束',
  },
  {
    value: 'manual-finish',
    label: '终止',
  },
]
const state = reactive({
  query: {
    compCname: '',
    startTime: [],
    endTime: [],
    contractName: '',
    startTimeBegin: '',
    startTimeEnd: '',
    endTimeBegin: '',
    endTimeEnd: '',
    productName: '',
    projectNo: '',
    contractNo: '',
    projectName: '',
    productNo: '',
    instStatus: '',
    sequenceId: '',
    starter: '',
    startDeptId: '',
    instSubject: '',
    processDefKey: '',
    groupCname: '',
    userCName: '',
    cyrUserCName: '',
    authType: '',
    startApp: '',
    startName: '',
    current: 1,
    size: 10,
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '实例号',
    prop: 'sequenceId',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '业务说明',
    prop: 'instSubject',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程名称',
    prop: 'processDefName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '产品名称',
    prop: 'productName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '项目名称',
    prop: 'projectName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '合同名称',
    prop: 'contractName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '开始时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '完成时间',
    prop: 'recCreateTime',
    align: 'center',
    editType: 'date-picker', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '状态',
  //   prop: 'instStatus',
  //   align: 'center',
  //   editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  // },
  {
    label: '状态',
    prop: 'instStatus',
    align: 'center',
    editable: false,
    filterable: false,
    sortable: false,
    modelValue: { inputValue: '' },
    editType: 'select',
    editConfig: {
      options: [
        {
          value: 'active',
          label: '正运行',
        },
        {
          value: 'suspend',
          label: '挂起',
        },
        {
          value: 'finish',
          label: '结束',
        },
        {
          value: 'manual-finish',
          label: '终止',
        },
      ],
    },
  },
  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const btnClick = (type) => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  authMode.value = type
  selectDiag.value = true
}
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
//删除
const deleteRow = () => {
  console.log(checkedRows.value, 'checkedRows.value')
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.processInstanceId) ids.push(item?.processInstanceId)
    })
  isTableLoading.value = true
  let par = {
    authUser: state.query.compCname,
    processInstanceIds: ids,
  }
  apiDeleteAuth(par)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
      }

      searchFn()
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const selectConfirm = () => {
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.processInstanceId) ids.push(item?.processInstanceId)
    })
  let par = {
    authMode: authMode.value,
    authUserName: userObj.value.userCName,
    processInstanceIds: ids,
  }
  console.log(userObj, 'userObj')
  if (authMode.value == 'SELECT') {
    par['authUser'] = userObj.value.loginName
  } else {
    par['userId'] = userObj.value.loginName
  }
  apiProcAuthInstAuth(par)
    .then((res) => {
      console.log(res, 'res')

      if (res.data.success) {
        selectDiag.value = false
        searchFn()
        useMessage().success(res.data.message)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      // 处理错误
    })
}
//重置
const resetFn = () => {
  state.query.cyrUserCName = ''
  state.query.compCname = ''
  state.query.startName = ''
  state.query.productName = ''
  state.query.groupCname = ''
  state.query.userCName = ''
}
const changeEvent = (e, type) => {
  if (type == 'fq_dept') state.query.startDeptId = ''
  if (type == 'fqr') {
    state.query.userCName = ''
    state.query.starter = ''
  }
  if (type == 'cyr') state.query.compCname = ''
  if (type == 'product') state.query.productName = ''
  if (type == 'fqxt') state.query.startApp = ''
  if (type == 'cyr') {
    state.query.cyrUserCName = ''
    state.query.compCname = ''
  }
}
const selectClick = (data, type) => {
  console.log(data, type, 'data123')
  if (type == 'fqr') {
    state.query.starter = data.loginName
  } else if (type == 'fq_dept') {
    state.query.startDeptId = data.groupEname
  } else if (type == 'cyr') {
    state.query.compCname = data.loginName
  } else if (type == 'sqr') {
    userObj.value = data
  } else if (type == 'fqxt') {
    state.query.startApp = data.appCode
  } else if (type == 'product') {
    state.query.productNo = data.productNo
  }
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  // console.log(rowData, 'rowData')
  // useMessageBox()
  //   .confirm(`您确认要置顶吗？`, '提示')
  //   .then(() => {
  //     apiExchangeSortIndex([rowData.id,0])
  //         .then((res) => {
  //           console.log(res, 'res123')
  //           if (res.data.success) {
  //             useMessage().success(res.data.message)
  //             searchFn()
  //           } else {
  //           }
  //         })
  //         .catch((error: any) => {})
  //   })
  //   .catch(() => {})
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  if (!state.query.cyrUserCName) {
    useMessage().warning('流程参与人必选')
    return
  }
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  console.log(type, 'type')
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  console.log(state.query.startTime, 'state.query.startTime')

  let par = {
    // startTimeBegin:
    userId: state.query.compCname,
    ...state.query,
    endTimeBegin: state.query.startTime ? state.query.startTime[0] : '',
    endTimeEnd: state.query.startTime ? state.query.startTime[1] : '',
    startTimeBegin: state.query.endTime ? state.query.endTime[0] : '',
    startTimeEnd: state.query.endTime ? state.query.endTime[1] : '',
  }
  delete par.startTime
  delete par.endTime
  apiQueryAuth(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const productloadMore = () => {
  if (loadMoreEnd.value && productPage.value > 1) return
  productPage.value++
  getProductList()
}
const getProductList = () => {
  let par = {
    current: productPage.value,
    size: 10,
  }
  apiQueryProduct(par)
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        // productList.value = res.data.data.result
        productList.value = productList.value.concat(res.data.data.result)
        if (productPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
//应用系统查询
const queryAppFunc = () => {
  let par = {
    appCode: '',
    appName: '',
    size: 999,
    current: 1,
  }
  apiQueryApp(par)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        appDataList.value = res.data.data.result
        // pageConfig.pageSize = Number(res.data.data.size)
        // pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const getQueryAll = () => {
  apiQueryProcessesDef()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        processArr.value = res.data.data.result.map((v) => {
          return {
            label: `${v.processDefinitionKey} - ${v.processDefinitionName}`,
            value: v.processDefinitionKey,
          }
        })
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryAll() //查询流程名称
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  queryAppFunc() //获取应用系统数据
  getProductList() //获取产品列表
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()
})
</script>
<style lang="less" scoped></style>
